﻿using System;
using MyCRM.Domain.Messages.Events;
using MyCRM.Infrastructure;
using MyCRM.Infrastructure.Messaging;
using MyCRM.Infrastructure.Repositories;
using MyCRM.ReadModel.ViewModels;

namespace MyCRM.ReadModel
{
    public class CustomerEventHandler : 
        IEventHandler<NewCustomerCreatedEvent>,
        IEventHandler<NewCustomerAddressCreatedEvent>,
        IEventHandler<CustomerAddressChangedEvent>
    {
        public IReadModelRepository Repository { get { return ServiceLocator.GetInstance<IReadModelRepository>(); }}

        public void Handle(NewCustomerCreatedEvent domainEvent)
        {
            Repository.Create(new CustomerViewModel()
                {
                    Id = domainEvent.CustomerId,
                    CustomerId = domainEvent.CustomerId,
                    LastName = domainEvent.LastName,
                    FirstName = domainEvent.FirstName,
                    Version = domainEvent.Version
                });
        }

        public void Handle(NewCustomerAddressCreatedEvent domainEvent)
        {
            var customer = Repository.FindBy<CustomerViewModel>(x => x.CustomerId == domainEvent.CustomerId);

            customer.City = domainEvent.City;
            customer.Number = domainEvent.Number;
            customer.PostalCode = domainEvent.PostalCode;
            customer.Street = domainEvent.Street;
            customer.Version = domainEvent.Version;

            Repository.Update(customer);
        }

        public void Handle(CustomerAddressChangedEvent domainEvent)
        {
            var customer = Repository.FindBy<CustomerViewModel>(x => x.CustomerId == domainEvent.CustomerId);

            customer.Street = domainEvent.Street;
            customer.Number = domainEvent.Number;
            customer.City = domainEvent.City;
            customer.PostalCode = domainEvent.PostalCode;
            customer.Version = domainEvent.Version;

            Repository.Update(customer);
        }
    }
}
